package com.example.controller;

import com.example.entity.Dept;
import com.example.entity.example.DeptExample;
import com.example.service.DeptService;
import com.example.util.ResultEntity;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/dept")
public class DeptController {

    @Autowired
    private DeptService deptService;

    @PreAuthorize("hasRole('ROLE_2') or hasRole('ROLE_3') ")
    @ResponseBody
    @RequestMapping("/get/all/depts.json")
    public ResultEntity<List<Dept>> getAllDepts(@RequestParam("page") Integer page,
                                                @RequestParam("limit") Integer limit,
                                                @RequestParam(value = "id", required = false) Integer id,
                                                @RequestParam(value = "name", required = false) String name
    ) {
        DeptExample example = new DeptExample();
        DeptExample.Criteria criteria = example.createCriteria();
        if (id != null) {
            criteria.andDidEqualTo(id);
        }
        if (name != null && !name.isEmpty()) {
            criteria.andDnameLike("%" + name + "%");
        }
        List<Dept> allDepts = deptService.getByExampleWithLimit(example, page, limit);
        int count = (int)deptService.getCountByExample(example);
        return ResultEntity.createResultEntity(0, null, count, allDepts);
    }

    @PreAuthorize("hasRole('ROLE_2') or hasRole('ROLE_3') ")
    @RequestMapping("/add/page.html")
    public String addPage() {
        return "include/add-dept";
    }

    @PreAuthorize("hasRole('ROLE_2') or hasRole('ROLE_3') ")
    @ResponseBody
    @RequestMapping("/add")
    public ResultEntity<Object> addDept(@RequestBody Dept dept) {
        deptService.addDept(dept);
        return ResultEntity.createResultEntity(0, null, 0, null);
    }

    @PreAuthorize("hasRole('ROLE_2') or hasRole('ROLE_3') ")
    @ResponseBody
    @RequestMapping("/remove")
    public ResultEntity<Object> removeById(@Param("id") Integer id) {
        try {
            deptService.removeById(id);
        } catch (Exception e) {
            return ResultEntity.createResultEntity(-1, e.getMessage(), 0, null);
        }
        return ResultEntity.createResultEntity(0, null, 0, null);
    }

    @PreAuthorize("hasRole('ROLE_2') or hasRole('ROLE_3') ")
    @ResponseBody
    @RequestMapping("/update")
    public ResultEntity<Object> updateById(@RequestBody Dept dept) {
        try {
            deptService.updateById(dept);
        } catch (Exception e) {
            return ResultEntity.createResultEntity(-1, e.getMessage(), 0, null);
        }
        return ResultEntity.createResultEntity(0, null, 0, null);
    }
}
